<template>
  <div class="page-container">
    <el-container>
      <el-aside width="200px" class="page-aside" v-drag v-collapse>
        <cm-organization-tree @handleNodeClick="handleNodeClick" />
      </el-aside>
      <el-main class="page-main">
        <!--表格内容栏-->
        <cm-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          :checkRowOpShow="checkRowOpShow"
          @handleTableOperator="handleTableOperator"
          @handleCellOperator="handleCellOperator"
        ></cm-table>
      </el-main>
    </el-container>

    <!--新增编辑界面-->
    <el-dialog
      :title="operator"
      width="65%"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <cm-form
        ref="dataForm"
        v-model="formData"
        :fields="columns"
        :rules="rules"
        :disabled="!dialogEdit"
      />
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible = false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="large"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible = false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import api from '@/http/api';
import {emitter} from '@/utils/bus';

const roles = ref({});
const filters = ref({
  code: "",
  name: "",
  status: "",
  organizationId: "",
  roleNames: "",
  valid: ""
}) // 分页查询条件
const filterFields = ref([
  {prop: "name", label: "姓名/职务/角色"},
  {prop: "status", label: "状态", type: "select", dicCode: "dicEmployeeStatus"},
  {prop: "valid", label: "是否有效", type: "select", dicCode: "dicValid"}
])
const columns = ref([
  {prop: "name", label: "姓名", minWidth: 90, click: true},
  {prop: "sex", label: "性别", minWidth: 80, type: 'radio', dicCode: "dicSex"},
  {prop: "username", label: "登录账号", minWidth: 110},
  {prop: "password", label: "登录密码", minWidth: 110, type: 'password', table: false, placeholder: (data) => {
      return dialogEdit.value && (data.id || '') !== '' ? '密码为空时不修改密码' : '';
    }
  },
  {prop: "organizationId", label: "默认科室", minWidth: 140, type: 'organization'},
  {prop: "belongIds", label: "归属科室", minWidth: 140, table: false, type: 'organization', leafSelect: false, multiple: true, appendToBody: true},
  {prop: "roleIds", label: "所属角色", minWidth: 110, cols: 2, type: 'checkbox', options: () => {
      return roles.value;
    }
  },
  {prop: "duty", label: "职务", minWidth: 100},
  {prop: "status", label: "状态", width: 90, sortable: false, type: 'radio', dicCode: "dicEmployeeStatus"},
  {prop: "ordinal", label: "排序", width: 90, type: 'number'},
  {prop: "valid", label: "是否有效", width: 90, sortable: false, type: 'radio', dicCode: 'dicValid'},
  {prop: "createTime", label: "创建时间", minWidth: 160, onlyShow: true},
]) // 分页列表字段
const operator = ref("") // 新增/编辑/查看弹窗标题
const dialogVisible = ref(false) // 弹窗是否显示
const dialogEdit = ref(true) // 弹窗表单是否可编辑
const editLoading = ref(false) // 弹窗表单提交状态
const rules = ref({
  name: [{required: true, message: "请输入姓名", trigger: "blur"}],
  status: [{required: true, message: "请选择员工状态", trigger: "change"}],
  valid: [{required: true, message: "请选择是否有效", trigger: "change"}],
  organizationId: [{required: true, message: "请选择默认科室", trigger: "change"}],
  //belongIds: [{required: true, message: "请选择归属科室", trigger: "change"}],
  mobile: [
    //{required: true, message: '请输入联系电话', trigger: 'change'},
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'change'}
  ],
})
const formData = ref({ roleIds: '' }) // 弹窗表单数据
const dataTable = ref()
const dataForm = ref()

const checkRowOpShow = (op, row) => {
  return !(op.name === "删除" && (row.username || "") !== "");
}

const handleNodeClick = (data) => {
  filters.value.organizationId = data.id;
  dataTable.value.findPage();
}

// 单元格操作
const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  operator.value = "查看";

  editLoading.value = true;
  api.post("/employee/queryBy", { id: row.id }).then((res) => {
    formData.value = Object.assign({}, res.data);
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
    editLoading.value = false;
  });

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
}

// 显示操作界面
const handleTableOperator = (button, row) => {
  if (button.buttonType === "edit") {
    editLoading.value = true;
    api.post(button.dataSourUrl, { id: row.id }).then((res) => {
      formData.value = Object.assign({}, res.data, { button: button });
      if (formData.value.organizationIds) {
        formData.value.belongIds = formData.value.organizationIds.join(",")
      }

      operator.value = button.name;
      dialogVisible.value = true;
      dialogEdit.value = true;
      nextTick(() => {
        dataForm.value && dataForm.value.clearValidate();
      });
      editLoading.value = false;
    });
  } else if (button.buttonType === "add") {
    formData.value = {
      roleIds: '',
      button: button,
      organizationId: filters.value.organizationId,
      status: "01",
      valid: '1'
    };

    operator.value = button.name;
    dialogVisible.value = true;
    dialogEdit.value = true;
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  } else {
    formData.value = { roleIds: '', button: button, status: "01", valid: '1' };
    operator.value = button.name;
    dialogVisible.value = true;
    dialogEdit.value = true;
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  }
}

const loadRoles = async () => {
  await api.post("/role/queryList", {}).then((res) => {
    let roleOptions = [];
    if (res.data && res.data.length > 0) {
      res.data.forEach(data => {
        roleOptions.push({key: data.id, value: data.name});
      });
    }
    roles.value = roleOptions;
  })
}

// 表单提交
const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("请确认是否提交？", "提示", { type: "info" }).then(() => {
        editLoading.value = true;
        if (formData.value.belongIds) {
          formData.value.organizationIds = formData.value.belongIds.split(",")
        }
        api.post(formData.value.button.dataDestUrl, formData.value)
          .then((res) => {
            ElMessage.success(res.message);
            dialogVisible.value = false;
            dataTable.value.findPage();
            editLoading.value = false;
            emitter.emit('employee.change');
          }).catch(() => {
          editLoading.value = false;
        });
      }).catch(() => {});
    } else {
      ElMessage.error("数据录入不正确，请重新检查！");
    }
  });
}

onMounted(() => {
  loadRoles();
});
</script>